package com.haiyuancloud.server.auth.handler;

import com.haiyuancloud.auth.service.TbLogLoginService;
import com.haiyuancloud.common.core.entity.HaiyuanAuthUser;
import com.haiyuancloud.common.core.entity.HaiyuanResponse;
import com.haiyuancloud.common.core.utils.HaiyuanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author haiyuan
 */
@Slf4j
@Component
public class HaiyuanWebLoginFailureHandler implements AuthenticationFailureHandler {

    @Resource
    private TbLogLoginService tbLogLoginService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException exception) throws IOException {
        String message;
        if (exception instanceof BadCredentialsException) {
            message = "用户名或密码错误！";
        } else if (exception instanceof LockedException) {
            message = "用户已被锁定！";
        } else {
            message = "认证失败，请联系网站管理员！";
        }
        insert(httpServletRequest,message);
        HaiyuanResponse haiyuanResponse = new HaiyuanResponse().message(message);
        HaiyuanUtil.makeFailureResponse(httpServletResponse, haiyuanResponse);
    }

    private  void insert (HttpServletRequest request,String message){
        Integer src = Integer.parseInt(request.getParameter("src"));
        Integer flag = 2;
        HaiyuanAuthUser currentUser = (HaiyuanAuthUser) request.getSession().getAttribute("authUser");
        tbLogLoginService.insert(  currentUser,  src,  flag,  message);
        request.getSession().removeAttribute("authUser");
    }
}
